package com.mulanweb.api.module.controller.wechat;

import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.JsonKit;
import com.mulanweb.db.common.Constant;
import com.mulanweb.db.common.RandomStringGenerator;
import com.mulanweb.db.common.WxParaFormatter;
import com.mulanweb.handler.wechat.JsApiTicketHandler;
import com.mulanweb.utils.SortUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.util.*;

/**
 * Created by Administrator on 2016/8/30.
 */
public class SignatureController extends Controller {

    /**
     * 调用微信js时需要config配置，此方法用于获取配置中的签名
     */
    public void getSignature(){
        String noncestr = RandomStringGenerator.getRandomStringByLength(32);
        String jsapi_ticket = JsApiTicketHandler.getJsApiTicket();
        Long timestamp = new Date().getTime();
        String url = getPara("url");

        StringBuffer string1 = new StringBuffer();
        string1.append("jsapi_ticket="+jsapi_ticket);
        string1.append("&noncestr="+noncestr);
        string1.append("&timestamp="+timestamp);
        string1.append("&url="+url);

        String signature = HashKit.sha1(string1.toString());
        System.out.println(signature);

        Map<String,String> resultPara = new HashMap<String,String>();
        resultPara.put("timestamp",timestamp+"");
        resultPara.put("noncestr",noncestr);
        resultPara.put("signature",signature);
        renderJson("DataList",resultPara);
    }

    public void getSignature2(){
        String noncestr = getPara("noncestr") ;
        String jsapi_ticket = JsApiTicketHandler.getJsApiTicket();
        String timestamp = "1472634564" ;
        String url = getPara("url") ;

        StringBuffer string1 = new StringBuffer();
        string1.append("jsapi_ticket="+jsapi_ticket);
        string1.append("&noncestr="+noncestr);
        string1.append("&timestamp="+timestamp);
        string1.append("&url="+url);

       /* Map<String,String> para = new HashMap<String,String>();
        para.put("jsapi_ticket",jsapi_ticket);
        para.put("noncestr",noncestr);
        para.put("timestamp",timestamp);
        para.put("url",url);

        para = SortUtil.mapSortRise(para) ;
        Set<String> keySet = para.keySet();
        Iterator<String> iter = keySet.iterator();
        StringBuffer string1 = new StringBuffer();
        while (iter.hasNext()) {
            String key = iter.next();
            string1.append("&"+key+"="+para.get(key));
            System.out.println(key + ":" + para.get(key));
        }*/

        //String string1= "jsapi_ticket"+jsapi_ticket+"&noncestr"+noncestr+"&timestamp="+timestamp+"&url="+url ;

        String signature = HashKit.sha1(string1.toString().replaceFirst("&",""));
        System.out.println(signature);

        Map<String,String> resultPara = new HashMap<String,String>();
        resultPara.put("timestamp",timestamp);
        resultPara.put("noncestr",noncestr);
        resultPara.put("signature",signature);
        renderJson("DataList",resultPara);
    }

    public void getPaySignature(){
        String nonceStr = getPara("nonceStr") ;
        String timeStamp = getPara("timeStamp") ;
        String appId = Constant.WeChatFinalValue.APPID;
        String packages = "prepay_id="+getPara("package");
        String  signType = getPara("signType");
        Map<String,String> para =new TreeMap<String,String>();
        para.put("nonceStr",nonceStr);
        para.put("timeStamp",timeStamp);
        para.put("appId",appId);
        para.put("package",packages);
        para.put("signType",signType);

        Set<String> keySet = para.keySet();
        Iterator<String> iter = keySet.iterator();
        StringBuffer string1 = new StringBuffer();
        while (iter.hasNext()) {
            String key = iter.next();
            string1.append("&"+key+"="+para.get(key));
            System.out.println(key + ":" + para.get(key));
        }

        String signature = HashKit.md5(string1.toString().replaceFirst("&",""));
        System.out.println(signature);

        Map<String,String> resultPara = new HashMap<String,String>();
        resultPara.put("timeStamp",timeStamp);
        resultPara.put("nonceStr",nonceStr);
        resultPara.put("signature",signature);
        renderJson("DataList",resultPara);
    }

    public void getPayPrepayId() throws Exception{
        String appid =Constant.WeChatFinalValue.APPID;//微信分配的公众账号ID（企业号corpid即为此appId）
        String mch_id =Constant.WeChatFinalValue.MCHID;//微信支付分配的商户号
        String device_info = "WEB";//设备号(终端设备号(门店号或收银设备ID)，注意：PC网页或公众号内支付请传"WEB")
        String nonce_str = "zenghf";//这是随机字符串
        String sign = null ; //所有参数按一定算法得到的签名
        String body = "新西兰旅游景点门票";//商品简单描述，该字段须严格按照规范传递，具体请见参数规定(https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_2)
        String out_trade_no = "20160912145133";//商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号(https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_2)
        int total_fee = 1; //订单总金额，单位为分，详见支付金额(地址同上)
        String spbill_create_ip = "192.168.1.1";//APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP。
        String notify_url = "http://bluefly.51vip.biz/mulan_xxl/admin/test/load";//接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。
        String trade_type = "JSAPI"; //JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付，统一下单接口trade_type的传参可参考这里MICROPAY--刷卡支付，刷卡支付有单独的支付接口，不调用统一下单接口
        //String openid = super.getSessionAttr("userId");
        String openid = "oULNBwOvt_D2A_8se1bQOQ06ky0w";
        Map<String,String> para= new HashMap<String,String>();
        para.put("appid",appid);
        para.put("mch_id",mch_id);
        para.put("device_info",device_info);
        para.put("nonce_str",nonce_str);
        para.put("body",body);
        para.put("out_trade_no",out_trade_no);
        para.put("total_fee",total_fee+"");
        para.put("spbill_create_ip",spbill_create_ip);
        para.put("notify_url",notify_url);
        para.put("trade_type",trade_type);
        para.put("openid",openid);
       // sign = Signature.getSign(para) ;
/*
        UnifiedorderService service = new UnifiedorderService();
        UnifiedorderReqData reqData = new UnifiedorderReqData();
        reqData.setAppid(Configure.getAppid());
        reqData.setMch_id(Configure.getMchid());
        reqData.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
        reqData.setSign(sign);
        reqData.setBody(body);
        reqData.setDevice_info(device_info);
        reqData.setOut_trade_no(out_trade_no);
        reqData.setTotal_fee(total_fee);
        reqData.setSpbill_create_ip(spbill_create_ip);
        reqData.setNotify_url(notify_url);
        reqData.setTrade_type(trade_type);
        String reXml = service.request(reqData);
        System.out.print("-------------:"+reXml);*/
        Map<String,String> paras = SortUtil.mapSortRise(para);
        //Map<String,String> paras = para;

        Set<String> keySet = para.keySet();
        Iterator<String> iter = keySet.iterator();
        StringBuffer string1 = new StringBuffer();
        Map<String,String> paraTest = new HashMap<String,String>();
        while (iter.hasNext()) {
            String key = iter.next();
            if(! "sign".equals(key)){
                string1.append("&"+key+"="+paras.get(key));
            }
            if("detail".equals(key)){
                paraTest.put(key, "<![CDATA["+ JsonKit.toJson(paras.get(key))+"]]>");
            }else{
                string1.append("&"+key+"="+paras.get(key));
                paraTest.put(key, para.get(key).toString());
            }
            System.out.println(key + ":" + para.get(key));
        }
        String string = string1.toString().replaceFirst("&","") + "&key=zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
        System.out.println(string);
        sign = HashKit.md5(string).toUpperCase();
        para.put("sign",sign);
        //paraTest.put("sign", Signature.getSign(para));

        System.out.println(sign);

        String xml = WxParaFormatter.mapToXml(paraTest);
        System.out.println(xml);
        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url) ;
        post.addHeader("Content/Type","application/xml");
        StringEntity stringEntity = new StringEntity(xml, ContentType.create("application/xml","UTF-8")) ;
        post.setEntity(stringEntity);
        CloseableHttpResponse resp = client.execute(post) ;
        int returnCode = resp.getStatusLine().getStatusCode() ;
        String str= "";
        if(200<=returnCode && 300>=returnCode){
            str = (EntityUtils.toString(resp.getEntity()));
        }

        Map<String,String> result = WxParaFormatter.xmlToMap(str);
        System.out.println(result);
        renderJson("DataList",result);
    }

}
